package com.zhny.aiot.syb.flow.plugin;

import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.model.IRequestMessage;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.modbus.ModbusNumDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.TaskEntity;
import com.zhny.aiot.syb.flow.plugin.model.FlowStoreEntry;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class FlowDevice extends ModbusNumDevice<FlowStoreEntry> {
    public FlowDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super (engine, factory, centerFacilities, entity);
    }

    @Override
    public FlowStoreEntry decode(ModemResponseMessage msg) {
        logger.info("start syb flow decode");
        ByteBuf buf = msg.getData();
        Float flow1=getFloat(buf);
        Float flowSpeed1=getFloat(buf);
        Float percentage1=buf.readFloat();
        Float flowPercentage1=buf.readFloat();
        long totalFlowHig1=((buf.readByte() << 8) &0x0000ff00|
                (buf.readByte() ) &0x000000ff|
                (buf.readByte() << 24) &0xff000000 |
                (buf.readByte() << 16) & 0x0000ff00);
        Float totalFlowLo1=getFloat(buf);
        Float totalFlow = totalFlowHig1 + totalFlowLo1;
        FlowStoreEntry entry = new FlowStoreEntry();
        entry.setFlow(String.format ("%.2f",flow1));
        entry.setFlowSpeed(String.format ("%.2f",flowSpeed1));
        entry.setTotalFlow( String.format ("%.2f",totalFlow));
        logger.info ("syb-flow[{}]",entry);
        return entry;
    }

    private float getFloat(ByteBuf buf){
        byte[] by = new byte[4];
//        buf.readBytes (by);
        by[2] =buf.readByte ();
        by[3] = buf.readByte ();
        by[0] = buf.readByte ();
        by[1] = buf.readByte ();

        ByteBuf buffer = Unpooled.wrappedBuffer(by);
        buffer.readerIndex(0);
        float floatValue = buffer.readFloat();

        return floatValue;
    }

    @Override
    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getData().readableBytes()== 24;
    }

    @Override
    protected IRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory().getRequestMessage(getConfig());
    }

    @Override
    protected void disposable() {

    }
}
